package com.spider.utils;

import com.spider.beans.BaseBean;
import org.apache.poi.xssf.usermodel.*;

import javax.swing.filechooser.FileSystemView;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class ExcelUtil {

    private String getCurrentTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM-dd-HH-mm-ss", Locale.CHINA);
        return simpleDateFormat.format(new Date(System.currentTimeMillis()));
    }

    public void createExcel(String fileName, String[] titles, List<? extends BaseBean> datas) {
        try {
            File xlsxFile = new File(FileSystemView.getFileSystemView().getHomeDirectory(), getCurrentTime() + "_" + fileName + ".xlsx");
            if (!xlsxFile.exists()) {
                xlsxFile.createNewFile();
            }

            FileOutputStream fileOutputStream = new FileOutputStream(xlsxFile);
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet(fileName);

            // 添加标题
            XSSFRow titleRow = sheet.createRow(0);
            for (int i = 0; i < titles.length; i++) {
                titleRow.createCell(i).setCellValue(titles[i]);
            }

            // 添加数据
            for (int i = 0; i < datas.size(); i++) {
                BaseBean data = datas.get(i);
                XSSFRow sheetRow = sheet.createRow(i + 1);

                String[] strings = data.convertArray();
                for (int j = 0; j < strings.length; j++) {
                    XSSFCell cell = sheetRow.createCell(j);
                    cell.setCellValue(strings[j]);
                }
            }

            workbook.write(fileOutputStream);
            fileOutputStream.close();

            System.out.println(fileName + "已保存至" + xlsxFile.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
